# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=cfitsio
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.6.2
pkgrel=3
epoch=1
pkgdesc="A library of C and Fortran subroutines for reading and writing data files in FITS (Flexible Image Transport System) data format (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://heasarc.gsfc.nasa.gov/fitsio/"
msys2_repository_url='https://github.com/HEASARC/cfitsio'
msys2_references=(
  "cpe: cpe:/a:nasa:cfitsio"
)
license=("spdx:CFITSIO")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-winpthreads")
depends=("${MINGW_PACKAGE_PREFIX}-curl"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread"
         "${MINGW_PACKAGE_PREFIX}-zlib")
source=("https://heasarc.gsfc.nasa.gov/FTP/software/fitsio/c/${_realname}-${pkgver}.tar.gz")
sha256sums=('66fd078cc0bea896b0d44b120d46d6805421a5361d3a5ad84d9f397b1b5de2cb')

prepare() {
  cd "${_realname}-${pkgver}"

  # Add static cflag
  echo "Cflags.private: -DCFITSIO_STATIC_DEFINE" >> ./cfitsio.pc.cmake
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  msg "Build static library"

  CFLAGS+=" -D_LARGEFILE_SOURCE=ON -D_FILE_OFFSET_BITS=64" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      ${extra_config[@]} \
      -DBUILD_SHARED_LIBS=OFF \
      -DUSE_PTHREADS=ON \
      -DTESTS=OFF \
      -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
      -S "${_realname}-${pkgver}" \
      -B "static-${MSYSTEM}"

  cmake --build "static-${MSYSTEM}"

  msg "Build shared library"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX" \
  CFLAGS+=" -D_LARGEFILE_SOURCE=ON -D_FILE_OFFSET_BITS=64" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      ${extra_config[@]} \
      -DBUILD_SHARED_LIBS=ON \
      -DUSE_PTHREADS=ON \
      -DTESTS=OFF \
      -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
      -S "${_realname}-${pkgver}" \
      -B "shared-${MSYSTEM}"

  cmake --build "shared-${MSYSTEM}"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "static-${MSYSTEM}"

  DESTDIR="${pkgdir}" cmake --install "shared-${MSYSTEM}"

  # Fix cmake files
  local PREFIX_WIN=$(cygpath -am ${MINGW_PREFIX})
  find "${pkgdir}${MINGW_PREFIX}/lib/cmake" -type f -name '*.cmake' \
      -exec sed -i -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" {} \;

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/licenses/License.txt "${pkgdir}${MINGW_PREFIX}"/share/licenses/${_realname}/LICENSE
}
